import { api, apiCommon } from "@/api/apiServer";
import { showToast, showLoadingToast, closeToast } from 'vant'

// 获取微信回调过来的code 和 state 换取token
const getWxCallBackUrlCode = async (vcode: string) => {
  console.log('==========获取code 换取token=============')
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    overlay: true
  })
  let resData:any = await api.getUserInfoByWxCode({
    code: vcode
  })
  console.log('========授权========')
  closeToast()
  if (resData.code === 200) {
    return resData
  } else {
    console.log(8899666)
    showToast({
      message: '授权失败',
      icon: 'none'
    })
  }
}

// 截取url中的 code
const getUrlCode = (name: string) => {
  return (
    decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) ||
    null
  )
}

// 特定的url进行处理
const urlDelP = (url:string, name:string) => {
  var urlArr = url.split('?')
  if (urlArr.length > 1 && urlArr[1].indexOf(name) > -1) {
    var query = urlArr[1]
    var obj:any = {}
    var arr:any[] = query.split('&')
    for (var i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split('=')
      obj[arr[i][0]] = arr[i][1]
    };
    delete obj[name]
    var urlte = urlArr[0] + '?' + JSON.stringify(obj).replace(/[\"\{\}]/g, '').replace(/\:/g, '=').replace(
      /\,/g, '&')
    return urlte
  } else {
    return url
  };
}

// 删除url中某个参数,并跳转
const funcUrlDel = (name:string) => {
  var loca = window.location
  var baseUrl = loca.origin + loca.pathname + '?'
  var query = loca.search.substr(1)
  if (query.indexOf(name) > -1) {
    var obj:any = {}
    var arr:any[] = query.split('&')
    for (var i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split('=')
      obj[arr[i][0]] = arr[i][1]
    };
    delete obj[name]
    var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, '').replace(/\:/g, '=').replace(/\,/g, '&')
    return url
  } else {
    return window.location.href
  };
}

// 跳转微信授权登录
const linkToWxLogin = () => {
  // 获取当前地址
  // let url:string = urlDelP(funcUrlDel('code'), 'state')
  let callbackUrl = encodeURIComponent(window.location.href) //获取当前页面地址作为回调地址
  //通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
  window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
    import.meta.env.VITE_APPID_WEIXIN
  }&redirect_uri=${callbackUrl}&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect`
}
// 获取微信code ,openid
const checkToken =  () => {
  return new Promise( async (resolve, reject) => {
    // 判断当前url是否有code 和 state，如果有，则说明是微信那边回调过来的
    // 则接收code 和 state ，去后台获取token
    let code = getUrlCode('code')
    await apiCommon.writeLog({
      str:'===========获取code=start============='
    })
    await apiCommon.writeLog({
      str:'code:'+code
    })
    await apiCommon.writeLog({
      str:'===========获取code=end============='
    })
    if (code) {
      // 获取到code
      let res = await getWxCallBackUrlCode(code)
      resolve(res)
    } else {
      // 跳转微信授权
      linkToWxLogin()
    }
  })
}

export default {
  checkToken
}
